<template>
  <div>
    <div style="font-size:18px;"><strong>2018年公司采购占比</strong></div>
    <div :style="{ height:`${height}px` }" :id="id"></div>
  </div>
</template>

<script>
import G2 from '@antv/G2'

export default {
  props: {
    charData: {
      type: Array,
      default: function () {
        return []
      }
    },
    width: {
      type: Number,
      default: 500
    },
    height: {
      type: Number,
      default: 500
    },
    id: String
  },
  data () {
    return {
      chart: null
    }
  },
  mounted () {
    this.drawChart(this.charData)
  },
  watch: {
    charData (val, oldVal) {
      this.drawChart(val)
    }
  },
  methods: {
    drawChart (datas) {
      this.chart && this.chart.destroy()
      this.chart = new G2.Chart({
        height: this.height,
        container: this.id, // 指定容器
        forceFit: true
      })
      this.chart.source(datas, {
        percent: {
          formatter: function (val) {
            val = val * 100 + '%'
            return val
          }
        }
      })
      this.chart.coord('theta') // 绘制饼图
      this.chart.tooltip({
        showTitle: false // 设置提示内容
      })
      this.chart.intervalStack().position('percent').color('item').label('percent', {
        offset: -40,
        textStyle: {
          textAlign: 'center',
          shadowBlur: 2,
          shadowColor: 'rgba(0, 0, 0, .45)'
        }
      }).tooltip('item*percent', function (item, percent) {
        percent = percent * 100 + '%'
        return {
          name: item,
          value: percent
        }
      }).style({
        // lineWidth: 1,
        stroke: 'fff'
      })
      this.chart.render()
    }
  }
}
</script>
